package com.yc.ssq.servlet;

import com.google.gson.Gson;
import com.yc.common.bean.Result;
import com.yc.ssq.dao.SsqDao;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(name = "UploadServlet", value = "/upload.s")
@MultipartConfig
public class UploadServlet extends HttpServlet {

    public static final String UPLOAD_DIR = "D:\\_文件柜\\116\\0625\\";
    private SsqDao dao = new SsqDao();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");

        // 假设上传文件字段 file
        Part filePart = request.getPart("file");
        // 构建文件对象
        String diskpath = UPLOAD_DIR + filePart.getSubmittedFileName();
        File fileObj = new File(diskpath);

        // 获取响应流, 字符集设置必须在 获取 out之前
        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = response.getWriter();
        // 判断文件是佛存在
        if (fileObj.exists()) {
            Result res = Result.failure("文件已经存在,上传失败!", null);
            String json = new Gson().toJson(res);
            out.write(json);
        } else {
            filePart.write(diskpath);
            dao.save(fileObj);
            Result res = Result.success("文件上传成功!", null);
            String json = new Gson().toJson(res);
            out.write(json);
        }
    }
}
